package com.iwinding.ladygg.bluetooth;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.exceptions.HyphenateException;
import com.iwinding.ladygg.AppForegroundStateManager;
import com.iwinding.ladygg.ICaneApplication;
import com.iwinding.ladygg.R;
import com.iwinding.ladygg.bluetooth.task.CountDownTimer;
import com.iwinding.ladygg.constant.SPConstant;
import com.iwinding.ladygg.modle.bean.EMSosMessageBean;
import com.iwinding.ladygg.net.RequestManager;
import com.iwinding.ladygg.net.callback.BaseRpCallback;
import com.iwinding.ladygg.net.callback.SendSOSCallback;
import com.iwinding.ladygg.net.request.PushSosReq;
import com.iwinding.ladygg.net.request.SendSOSReq;
import com.iwinding.ladygg.net.response.BaseRopnse;
import com.iwinding.ladygg.net.response.LoginRp;
import com.iwinding.ladygg.net.response.SendSOSRp;
import com.iwinding.ladygg.net.response.SosDetailRp;
import com.iwinding.ladygg.ui.act.ChatActivity;
import com.iwinding.ladygg.ui.act.SosDetailActivity;
import com.iwinding.ladygg.utils.DateUtil;
import com.iwinding.ladygg.utils.LogUtil;
import com.iwinding.ladygg.utils.SPUtils;
import com.iwinding.ladygg.utils.SystemUtil;
import com.iwinding.ladygg.utils.ToastUtil;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by hezhiyong on 2017/5/20.
 */

public class TMApi {

    private static TMApi instance;

    protected static Context mContext;

    private ExecutorService executorService = null;

    private boolean isget = true;

    private static CountDownTimer cdt;

    public TMApi() {
        executorService = Executors.newCachedThreadPool();
//        executorService.execute(new Runnable() {
//            @Override
//            public void run() {
//                int sleepTime = 5000;
//                while (isget) {
//                    try {
//                        Thread.sleep(sleepTime);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    AMMapHelper.getInstance().startLocation();
//                    AMapLocation location = AMMapHelper.getInstance().getmLocationInfo();
//                    float speed = location.getSpeed();
//                    LogUtil.i("@hzy", "----------speed:" + speed);
//                    if (speed >= 0 && speed < 0.3) {
//                        sleepTime = 20000;
//                    } else if (speed >= 0.3 && speed < 1.5) {
//                        sleepTime = 5000;
//                    } else if (speed >= 1.5) {
//                        sleepTime = 2000;
//                    }
//                }
//            }
//        });
    }

    public static TMApi getInstance() {
        if (instance == null) {
            synchronized (TMApi.class) {
                if (instance == null) {
                    instance = new TMApi();
                }
            }
        }
        return instance;
    }

    public void initContext(Context context) {
        mContext = context;
        if (null == executorService) {
            executorService = Executors.newCachedThreadPool();
        }
    }

    public void onDistory() {
        isget = false;
        try {
            cdt.cancel();
            executorService.shutdown();
            executorService.shutdownNow();
        } catch (Exception e) {

        }
        cdt = null;
        executorService = null;
    }

    public void sendSOS(final AMapLocation locationInfo) {
        LogUtil.i("@hzy", "-----------sendSOS");
        if (null == locationInfo) {
            if (AppForegroundStateManager.getInstance().isAppInForeground()) {
                final Activity currentAct = AppForegroundStateManager.getInstance().getForegroundActivity();
                currentAct.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.openBaseToast(currentAct, R.string.location_fail_toast, Toast.LENGTH_SHORT);
                    }
                });
            }
            return;
        }
//        boolean ican = isCanSendSOS(mContext);
//        if (!ican) {
//            return;
//        }
        final SendSOSReq sendSOSReq = new SendSOSReq();
        sendSOSReq.latitude = String.valueOf(locationInfo.getLatitude());
        sendSOSReq.longitude = String.valueOf(locationInfo.getLongitude());
        sendSOSReq.address = locationInfo.getAddress();
        sendSOSReq.sendTime = DateUtil.getCurrentSecondTimeString();
        RequestManager.postSendSOS(mContext, sendSOSReq, new SendSOSCallback() {
            @Override
            public void onResult(final SendSOSRp sendSOSRp) {
                if (null == sendSOSRp && TextUtils.isEmpty(sendSOSRp.sosId)) {
                    ToastUtil.openBaseToast(mContext, R.string.send_sos_fail, Toast.LENGTH_SHORT);
                    return;
                }
                setLastSOS(mContext);
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        LoginRp loginRp = ((ICaneApplication) instance.mContext.getApplicationContext()).getmLoginRp();
                        sendSOSContent(createEMSosMessageBean(sendSOSRp.sosId, locationInfo, loginRp));
                    }
                });
                pushSos(sendSOSRp);
                createAreDialog(sendSOSRp.sosId);
            }

            @Override
            public void onFail(String errorMsg) {
                ToastUtil.openBaseToast(mContext, errorMsg, Toast.LENGTH_SHORT);
            }
        });
    }

    public void pushSos(final SendSOSRp sendSOSRp) {
        final int count = SPUtils.getSpPropertyInt(mContext, SPConstant.REPEAT, 4);
        final int frequency = SPUtils.getSpPropertyInt(mContext, SPConstant.FREQUENCY, 1);
        if (cdt != null) {
            cdt.cancel();
            cdt = null;
        }
        LogUtil.i("@hzy", "-----------pushSos:次数" + count + "---间隔：" + frequency);
        cdt = new CountDownTimer(count * frequency * 1000 * 60, frequency * 1000 * 60) {
            //        cdt = new CountDownTimer(count * frequency  * 1000 * 60, frequency  * 1000 *60) {
            @Override
            public void onTick(long millisUntilFinished) {
                pushNetSos(sendSOSRp);
            }

            @Override
            public void onFinish() {
                pushNetSos(sendSOSRp);
            }
        };
        cdt.start();
    }

    private void pushNetSos(final SendSOSRp sendSOSRp) {
        //推送
        PushSosReq pushSosReq = new PushSosReq();
        pushSosReq.sosId = sendSOSRp.sosId;
        RequestManager.postPushSos(mContext, pushSosReq, new BaseRpCallback<BaseRopnse>() {
            @Override
            public BaseRopnse parseResponse(BaseRopnse response, int id) {
                return response;
            }

            @Override
            public void onResult(BaseRopnse baseRopnse) {
                LogUtil.i("@hzy", "-----------pushSos:" + sendSOSRp.sosId + "       isOk");
            }

            @Override
            public void onFail(String errorMsg) {
                ToastUtil.openBaseToast(mContext, errorMsg, Toast.LENGTH_SHORT);
            }
        });
    }


    public void handleSos(String sosid, String address, SosDetailRp sosDetailRp) {
        LoginRp loginRp = ((ICaneApplication) mContext.getApplicationContext()).getmLoginRp();
        handleSOSContent(createHandleEMSosMessageBean(sosid, address, sosDetailRp), sosDetailRp);
        if (loginRp == null || TextUtils.isEmpty(sosDetailRp.groupId)) {
            return;
        }
        startChat(mContext, sosDetailRp.groupId);
    }

    private static void startChat(Context mContext, String userId) {
        Intent intent = new Intent(mContext, ChatActivity.class).putExtra("userId", userId);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        mContext.startActivity(intent);
    }

    private AlertDialog alertDialog = null;

    private void createAreDialog(final String sosid) {
        if (alertDialog != null) {
            alertDialog = null;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("发送SOS急救成功");
        builder.setNeutralButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                alertDialog.dismiss();
            }
        });
        builder.setPositiveButton("查看详情", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent detail = new Intent(mContext, SosDetailActivity.class);
                detail.putExtra(SosDetailActivity.SOSID, String.valueOf(sosid));
                detail.putExtra(SosDetailActivity.ISME, true);
                mContext.startActivity(detail);
            }
        });
        alertDialog = builder.create();
        alertDialog.show();
    }


    private void sendSOSContent(EMSosMessageBean bean) {
        String content = "SOS紧急呼救";
        LoginRp loginRp = SystemUtil.getLoginRp(mContext);
        EMMessage message = EMMessage.createTxtSendMessage(content, loginRp.groupId);
        //如果是群聊，设置chattype，默认是单聊
        message.setChatType(EMMessage.ChatType.GroupChat);
        if (bean != null) {
            message.setAttribute(EMSosMessageBean.Attribute.VALUES[0], Integer.parseInt(bean.type));
            message.setAttribute(EMSosMessageBean.Attribute.VALUES[1], bean.helper);
            message.setAttribute(EMSosMessageBean.Attribute.VALUES[2], bean.helpTime);
            message.setAttribute(EMSosMessageBean.Attribute.VALUES[3], bean.userID);
            message.setAttribute(EMSosMessageBean.Attribute.VALUES[4], bean.uname);
            message.setAttribute(EMSosMessageBean.Attribute.VALUES[5], bean.mobile);
            message.setAttribute(EMSosMessageBean.Attribute.VALUES[6], bean.address);
            message.setAttribute(EMSosMessageBean.Attribute.VALUES[7], bean.sosID);
            message.setAttribute(EMSosMessageBean.Attribute.VALUES[8], bean.longtitude);
            message.setAttribute(EMSosMessageBean.Attribute.VALUES[9], bean.latitude);
            message.setAttribute(EMSosMessageBean.Attribute.VALUES[10], bean.time);
        }
//        String type = message.getStringAttribute("type", "");
        // 发送消息
        EMClient.getInstance().chatManager().sendMessage(message);
        try {
            EMClient.getInstance().groupManager().changeGroupName(loginRp.groupId, loginRp.getName() + "的SOS");
        } catch (HyphenateException e) {
            e.printStackTrace();
        }
    }

    private void handleSOSContent(EMSosMessageBean bean, SosDetailRp sosDetailRp) {
        String content = "SOS紧急呼救";
        if (sosDetailRp == null || TextUtils.isEmpty(sosDetailRp.groupId)) {
            return;
        }
        EMMessage message = EMMessage.createTxtSendMessage(content, sosDetailRp.groupId);
        //如果是群聊，设置chattype，默认是单聊
        message.setChatType(EMMessage.ChatType.GroupChat);
        if (bean != null) {
            message.setAttribute(EMSosMessageBean.Attribute.VALUES[0], Integer.parseInt(bean.type));
            message.setAttribute(EMSosMessageBean.Attribute.VALUES[1], bean.helper);
            message.setAttribute(EMSosMessageBean.Attribute.VALUES[2], bean.helpTime);
            message.setAttribute(EMSosMessageBean.Attribute.VALUES[3], bean.userID);
            message.setAttribute(EMSosMessageBean.Attribute.VALUES[4], bean.uname);
            message.setAttribute(EMSosMessageBean.Attribute.VALUES[5], bean.mobile);
            message.setAttribute(EMSosMessageBean.Attribute.VALUES[6], bean.address);
            message.setAttribute(EMSosMessageBean.Attribute.VALUES[7], bean.sosID);
            message.setAttribute(EMSosMessageBean.Attribute.VALUES[8], bean.longtitude);
            message.setAttribute(EMSosMessageBean.Attribute.VALUES[9], bean.latitude);
            message.setAttribute(EMSosMessageBean.Attribute.VALUES[10], bean.time);
        }
//        Map<String, Object> exts = message.ext();
//        if (exts != null && exts.size() != 0) {
//            String type = convertStr(exts.get(EMSosMessageBean.Attribute.VALUES[0]));
//        }
        // 发送消息
        EMClient.getInstance().chatManager().sendMessage(message);
    }

    /**
     * 转换成Str
     *
     * @param object
     * @return
     */
    private String convertStr(Object object) {
        if (object instanceof String)
            return (String) object;
        if (object == null) {
            return null;
        }
        return String.valueOf(object);
    }

    EMSosMessageBean createEMSosMessageBean(String sosId, AMapLocation locationInfo, LoginRp loginRp) {
        EMSosMessageBean bean = new EMSosMessageBean();
        bean.type = "0";
        bean.helper = "";
        bean.helpTime = "";//处理时间
        bean.userID = loginRp.userId;//
        bean.uname = loginRp.getName();//被救人别名
        bean.mobile = loginRp.mobile;//手机号
        bean.address = locationInfo.getAddress();//地址
        bean.sosID = sosId;//急救ID
        bean.longtitude = String.valueOf(locationInfo.getLatitude());//地理
        bean.latitude = String.valueOf(locationInfo.getLongitude());//地理
        bean.time = DateUtil.getCurrentSecondTimeString();//急救时间

        return bean;
    }

    EMSosMessageBean createHandleEMSosMessageBean(String sosid, String address, SosDetailRp sosDetailRp) {
        LoginRp loginRp = SystemUtil.getLoginRp(mContext);
        EMSosMessageBean bean = new EMSosMessageBean();
        bean.type = "1";
        if (loginRp != null) {
            bean.helper = loginRp.getName();
            bean.helpTime = DateUtil.getCurrentSecondTimeString();//处理时间
            bean.mobile = loginRp.mobile;//手机号
            bean.userID = loginRp.userId;//
        }
        bean.uname = TextUtils.isEmpty(sosDetailRp.nickName) ? sosDetailRp.uname : sosDetailRp.nickName;//被救人别名
        bean.address = address;//地址
        bean.sosID = sosid;//急救ID
        bean.longtitude = sosDetailRp.longitude;//地理
        bean.latitude = sosDetailRp.latitude;//地理
        try {
            bean.time = DateUtil.getTime(sosDetailRp.sendTime);
        } catch (Exception e) {
            bean.time = sosDetailRp.sendTime;
        }
        return bean;
    }

    private void setLastSOS(final Context mContext) {
        SPUtils.putSpProperty(mContext, "last_sos_timestamp", System.currentTimeMillis());
    }

//    private boolean isCanSendSOS(final Context mContext) {
//        long last_sos_timestamp = SPUtils.getSpPropertyLong(mContext, "last_sos_timestamp", 0);
//        long now_sos_timestamp = System.currentTimeMillis();
//        int frequency = SPUtils.getSpPropertyInt(mContext, SPConstant.FREQUENCY, 1);
//        int count = SPUtils.getSpPropertyInt(mContext, SPConstant.REPEAT, 1);
//        if (now_sos_timestamp - last_sos_timestamp >= frequency * 60 * 1000 || count == 0) {
//            return true;
//        }
//        return false;
//    }

}
